const db = require('../config/database');
const Package = require('../models/Package');
const Tag = require('../models/Tag');
const PackageTag = require('../models/PackageTag');
const DownloadStat = require('../models/DownloadStat');
const Discussion = require('../models/Discussion');

async function initDatabase() {
  try {
    console.log('开始初始化数据库...');
    
    // 创建一些测试标签
    const tags = await Tag.bulkCreate([
      { name: '前端框架', count: 0 },
      { name: '后端框架', count: 0 },
      { name: '工具库', count: 0 },
      { name: 'UI组件', count: 0 },
      { name: '测试工具', count: 0 },
      { name: '构建工具', count: 0 },
      { name: '数据库', count: 0 },
      { name: '网络请求', count: 0 },
      { name: '日期处理', count: 0 },
      { name: '图表可视化', count: 0 }
    ]);
    
    console.log('标签创建完成');
    
    // 创建一些测试包
    const packages = await Package.bulkCreate([
      {
        name: 'vue',
        description: 'The Progressive JavaScript Framework',
        description_zh: '渐进式JavaScript框架',
        author: 'Evan You',
        version: '3.3.4',
        downloads: 15000000,
        score: 4.8,
        npm_url: 'https://www.npmjs.com/package/vue',
        github_url: 'https://github.com/vuejs/vue',
        is_popular: true
      },
      {
        name: 'react',
        description: 'A JavaScript library for building user interfaces',
        description_zh: '用于构建用户界面的JavaScript库',
        author: 'Facebook',
        version: '18.2.0',
        downloads: 20000000,
        score: 4.9,
        npm_url: 'https://www.npmjs.com/package/react',
        github_url: 'https://github.com/facebook/react',
        is_popular: true
      },
      {
        name: 'express',
        description: 'Fast, unopinionated, minimalist web framework for node.',
        description_zh: '快速、无偏见、极简的Node.js Web框架',
        author: 'TJ Holowaychuk',
        version: '4.18.2',
        downloads: 25000000,
        score: 4.7,
        npm_url: 'https://www.npmjs.com/package/express',
        github_url: 'https://github.com/expressjs/express',
        is_popular: true
      },
      {
        name: 'lodash',
        description: 'A modern JavaScript utility library delivering modularity, performance, & extras.',
        description_zh: '现代JavaScript实用工具库，提供模块化、性能和额外功能',
        author: 'John-David Dalton',
        version: '4.17.21',
        downloads: 30000000,
        score: 4.6,
        npm_url: 'https://www.npmjs.com/package/lodash',
        github_url: 'https://github.com/lodash/lodash',
        is_popular: true
      },
      {
        name: 'axios',
        description: 'Promise based HTTP client for the browser and node.js',
        description_zh: '基于Promise的浏览器和Node.js HTTP客户端',
        author: 'Matt Zabriskie',
        version: '1.4.0',
        downloads: 18000000,
        score: 4.5,
        npm_url: 'https://www.npmjs.com/package/axios',
        github_url: 'https://github.com/axios/axios',
        is_popular: true
      }
    ]);
    
    console.log('包创建完成');
    
    // 创建包标签关联
    const packageTagRelations = [
      { package_id: packages[0].id, tag_id: tags[0].id }, // vue - 前端框架
      { package_id: packages[1].id, tag_id: tags[0].id }, // react - 前端框架
      { package_id: packages[2].id, tag_id: tags[1].id }, // express - 后端框架
      { package_id: packages[3].id, tag_id: tags[2].id }, // lodash - 工具库
      { package_id: packages[4].id, tag_id: tags[7].id }, // axios - 网络请求
    ];
    
    await PackageTag.bulkCreate(packageTagRelations);
    
    // 更新标签计数
    for (const tag of tags) {
      const count = await PackageTag.count({ where: { tag_id: tag.id } });
      await tag.update({ count });
    }
    
    console.log('包标签关联创建完成');
    
    // 创建一些下载统计数据
    const downloadStats = [];
    const now = new Date();
    
    for (const pkg of packages) {
      for (let i = 30; i >= 0; i--) {
        const date = new Date(now);
        date.setDate(date.getDate() - i);
        
        downloadStats.push({
          package_id: pkg.id,
          date: date.toISOString().split('T')[0],
          downloads: Math.floor(Math.random() * 10000) + 1000
        });
      }
    }
    
    await DownloadStat.bulkCreate(downloadStats);
    console.log('下载统计数据创建完成');
    
    // 创建一些讨论数据
    const discussions = [];
    for (const pkg of packages) {
      discussions.push({
        package_id: pkg.id,
        user_name: '测试用户1',
        title: `关于 ${pkg.name} 的使用经验分享`,
        content: `这是关于 ${pkg.name} 的讨论，这个包非常好用！我已经在多个项目中使用了它，效果很不错。`,
        likes: Math.floor(Math.random() * 50)
      });
      
      discussions.push({
        package_id: pkg.id,
        user_name: '测试用户2',
        title: `${pkg.name} 使用中遇到的问题求助`,
        content: `我在使用 ${pkg.name} 时遇到了一些问题，有人能帮忙解答吗？具体问题是...`,
        likes: Math.floor(Math.random() * 20)
      });
    }
    
    // 添加一些不关联包的通用讨论
    discussions.push({
      package_id: null,
      user_name: 'admin',
      title: '欢迎来到npm-explore讨论区',
      content: '这里是npm包探索和讨论的地方，欢迎大家分享经验、提出问题！',
      likes: 100
    });
    
    discussions.push({
      package_id: null,
      user_name: '开发者',
      title: 'JavaScript生态系统发展趋势讨论',
      content: '让我们来讨论一下JavaScript生态系统的发展趋势，哪些技术值得关注？',
      likes: 75
    });
    
    await Discussion.bulkCreate(discussions);
    console.log('讨论数据创建完成');
    
    console.log('数据库初始化完成！');
    
  } catch (error) {
    console.error('数据库初始化失败:', error);
  }
}

module.exports = { initDatabase };

// 如果直接运行此脚本
if (require.main === module) {
  initDatabase().then(() => {
    process.exit(0);
  }).catch(error => {
    console.error(error);
    process.exit(1);
  });
}